class_name HurtboxComponent
extends Area2D

signal hit_by_hitbox(attribute:HitboxComponent.ATTRIBUTE_TYPE,is_damage:bool,damage:float)

@export var health_component: HealthComponent
@export var obj: Node2D
#考虑了一下，还是在这里对它能收到的伤害类型进行维护
#因为有一个类型，就搞一个碰撞检测层太麻烦了
@export var attributes : Array[HitboxComponent.ATTRIBUTE_TYPE]

var peer_id_filter: int = -1
var disable_collisions: bool

#可以被伤害
var disable_damage: bool = false


func _ready() -> void:
	area_entered.connect(_on_area_entered)


func _handle_hit(hitbox_component: HitboxComponent):
	#碰撞的物體已經觸發過了，或者當前不想再被碰撞
	if hitbox_component.is_hit_handled || disable_collisions:
		return
	
	#如果当前被设置为不被伤害，当前伤害值大于0，我们将其跳过碰撞
	if disable_damage && hitbox_component.damage > 0.0:
		return
	
	#如果当前可以被伤害的属性与伤害属性不符，跳过碰撞逻辑
	if is_not_hurt(hitbox_component):
		return
		
	
	hitbox_component.register_hurtbox_hit(self)
	
	
	var damage: float = 0.0

	
	#如果防御姿态，那么就受到较少的伤害
	if obj and obj.defence and hitbox_component.damage > 0.0:
		damage = hitbox_component.damage/4
	else:
		damage = hitbox_component.damage
		
	health_component.damage(damage)

	hit_by_hitbox.emit(hitbox_component.attribute,damage > 0.0,damage)



func _on_area_entered(other_area: Area2D):
	if !is_multiplayer_authority() || other_area is not HitboxComponent:
		return
	
	var hitbox_component: HitboxComponent = other_area
	if peer_id_filter > -1 && hitbox_component.source_peer_id != peer_id_filter:
		return
	
	_handle_hit.call_deferred(other_area)


func is_not_hurt(hitbox_component: HitboxComponent) -> bool:
	
		#如果当前可以被伤害的属性与伤害属性不符，跳过碰撞逻辑
	if attributes.size()>0:
		if !attributes.has(hitbox_component.attribute):
			return true
	return false
